﻿using LY.Common.Utils.Sf_Struct;
using LY.Entity;
using LY.Entity.Entities;
using LY.Entity.Jsons;
using LY.Entity.PageSearch;
using LY.Entity.SearchEntity;
using LY.Interface;
using LY.ShengPayApi.Model;
using LY.PdfToWord;
using QJ.CMS.Filters;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using LY.Extension;
using LY.Common.Utils.Sign;
using LY.Common.Utils;

namespace QJ.CMS.Controllers
{
    public class ClaimsController : MyControllerBase
    {
        private IClaimsService _cservice;
        private IT_ProjectService _pservice;
        private IFundsFlowService _fservice;
        private IInvestService _investService;
        private IMemberService _memberService;
        private IScoreService _scoreService;
        private static string _sftAddress = ConfigurationManager.AppSettings["SftAddress"];
        private static string _merchantNo = ConfigurationManager.AppSettings["merchantNo"];
        private static string _backAddress = ConfigurationManager.AppSettings["BackAddress"];
        private static string _apiAddress = ConfigurationManager.AppSettings["ApiAddress"];
        private static string _zQFee = ConfigurationManager.AppSettings["ZQFee"];

        public ClaimsController(IClaimsService cService, IT_ProjectService pService, IFundsFlowService fservice, IInvestService investService, IMemberService memberService, IScoreService scoreService)
        {
            _cservice = cService;
            _pservice = pService;
            _fservice = fservice;
            _investService = investService;
            _memberService = memberService;
            _scoreService = scoreService;
        }

        //
        // GET: /Claims/ 债权控制器

        public ActionResult Index()
        {
            ViewData.Add("plist_new", _cservice.GetProjects(1, 4));
            ViewData.Add("plist_notnew", _cservice.GetProjects(0, 5));
            ViewBag.ilist_hot = _cservice.GetHotInvestors(10);//排名
            //ViewBag.Amounts = _cservice.GetAmountsByPid(null) / 10000;//投资金额统计
            //ViewBag.Numbers = _cservice.GetHotInvestors(null, null).Count;//投资人数统计
            //ViewBag.Profits = _cservice.GetInvestProfits("");//统计收益 
            return View();
        }

        #region 我的投资
        [MyAuthorization]
        public ActionResult MyInvest()
        {
            return View();
        }

        //我的投资记录
        [MyAuthorization]
        [HttpPost]
        public ActionResult GetProjectOfMine(FormCollection form, ClaimsSearch condition)
        {
            U_Member u = Session["CurrentUser"] as U_Member;
            if (u != null)
            {
                PageView view = new PageView(form);
                string colkey = form["colkey"];
                string colsinfo = form["colsinfo"];
                PagedList<T_Project_EX> plist = _cservice.GetProjectOfMine(view, u.ID.ToString(), condition);
                JsonQTable at = JsonQTable.ConvertFromPagedList<T_Project_EX>(plist, colkey, colsinfo.Split(','));
                return Json(at);
            }
            else
            {
                return RedirectToAction("Index", "Login");
            }
        }

        [HttpPost]
        public ActionResult DeleteMyInvest(string id)
        {
            JsonSMsg msg = new JsonSMsg();
            int result = _cservice.DeleteMyInvest(id);
            if (result > 0)
            {
                msg.Status = 1;
                msg.Message = "删除成功！";
                msg.Data = Url.Action("MyInvest");
            }
            else
            {
                msg.Status = -1;
                msg.Message = "删除失败！";
            }
            return Json(msg);
        }

        //投资记录
        [HttpPost]
        public ActionResult GetInvestors(FormCollection form, string pid)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<T_Investment_EX> ilist = _cservice.GetInvestors(view, pid);
            JsonQTable at = JsonQTable.ConvertFromPagedList<T_Investment_EX>(ilist, colkey, colsinfo.Split(','));
            return Json(at);
        }
        #endregion

        #region 具体投资页面
        public ActionResult ToInvest(string id)
        {
            //获取当前用户的余额
            //账户资金
            U_Member mm = (U_Member)Session["CurrentUser"];
            T_Project_EX project = _cservice.GetProjectById(id);
            decimal pamounts = _cservice.GetAmountsByPid(project.ID.ToString());
            ViewBag.IsLoading = 0;
            if (mm != null)
            {
                ViewBag.IsLoading = 1;
                if (string.IsNullOrEmpty(mm.SFTUserId))
                {
                    ViewBag.totalAmount = 0;
                    ViewBag.availableAmount = 0;
                    ViewBag.frozenAmount = 0;
                }
                else
                {
                    string strJson = SelectSftUserBalance();
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    Type type = typeof(Dictionary<string, string>);
                    dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
                    if (dic["errorMessage"] == "平台用户未开户")
                    {
                        ViewBag.totalAmount = 0;
                        ViewBag.availableAmount = 0;
                        ViewBag.frozenAmount = 0;
                    }
                    else
                    {
                        ViewBag.totalAmount = dic["totalAmount"];
                        ViewBag.availableAmount = dic["availableAmount"];
                        ViewBag.frozenAmount = dic["frozenAmount"];
                        ViewBag.agreeWithhold = dic["agreeWithhold"];
                        //ViewBag.myScore = _scoreService.GetScoreByMID(mm.ID);
                    }
                }
                ViewBag.myScore = _scoreService.GetScoreByMID(mm.ID);
            }
            ViewData.Add("doc", _cservice.GetDocImage(id));
            ViewBag.RZJinDu = Math.Round(pamounts * 100 / (decimal)project.TotalLoan, 1);//进度百分比
            ViewBag.AvaAmounts = Math.Round((decimal)project.TotalLoan - pamounts, 0);//剩余的投标金额
            ViewBag.IsNewProject = mm == null ? true : _cservice.IsGreenHand(mm.ID.ToString());
            ViewBag.ProjectStatus = _cservice.GetProjects(id).ProjectStatus;
            return View(project);
        }

        //投资确认 弹出一个层
        [MyAuthorization]
        public ActionResult ConfirmInvest(string id)
        {
            U_Member m = Session["CurrentUser"] as U_Member;
            T_Project_EX project = _cservice.GetProjectById(id);
            if (m != null)
            {
                ViewBag.Amount = 0;
                ViewBag.availableAmount = 0;
                ViewBag.ProjectId = id;
                if (Request["amount"] != null)
                {
                    //这里防止对方修改js代码，虽然我暂时不会改。
                    try
                    {
                        int temp = Convert.ToInt32(Request["amount"]);
                        if (temp % project.MinTenderAmount == 0)
                        {
                            ViewBag.Amount = Request["amount"];
                        }
                        else
                        {
                            ViewBag.Amount = project.MinTenderAmount;
                        }
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Amount = project.MinTenderAmount;
                    }

                }
                if (Request["availableAmount"] != null)
                {
                    ViewBag.availableAmount = Request["availableAmount"];
                }

                if (!string.IsNullOrEmpty(m.SFTUserName))
                {
                    Dictionary<string, string> dic = GetBalance();
                    ViewBag.agreeWithhold = dic["agreeWithhold"];
                    ViewBag.availableAmount = dic["availableAmount"];
                    ViewBag.myScore = _scoreService.GetScoreByMID(m.ID);
                }

                return View(project);
            }
            else
            {
                return RedirectToAction("Index", "Login");
            }
        }

        public ActionResult ConfirmMiddlePage(string issueBidNo, string submitBidNo, string userName, string creditAmount, string score, string projectId)
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            int myscore = 0;
            try
            {
                myscore = Convert.ToInt32(score);//获取积分
                if (myscore > _scoreService.GetScoreByMID(member.ID)) //当用户手动修改积分该成很多的时候，让它直接为0
                {
                    myscore = 0;
                }
            }
            catch (Exception ex)
            {
                myscore = 0;
            }
            string discountAmount = (myscore * 0.01).ToString("0.00");
            string[] array = new string[9];
            array[0] = "merchantNo=" + _merchantNo;
            array[1] = "timestamp=" + time;
            array[2] = "issueBidNo=" + issueBidNo;
            array[3] = "submitBidNo=" + submitBidNo;
            array[4] = "userName=" + userName;
            array[5] = "creditAmount=" + creditAmount;
            array[6] = "discountAmount=" + discountAmount;
            array[7] = "callback=" + _backAddress + "/Claims/ZhaiQuanConfirmCallBack";
            array[8] = "notifyUrl=" + _backAddress + "/Pay/ZhaiQuanConfirmNotifyUrl";

            AddFundFlowToDB(member, myscore, submitBidNo, creditAmount, projectId);
            ViewBag.sftAddress = _sftAddress;
            ViewBag.merchantNo = _merchantNo;
            ViewBag.sfttimestamp = time;
            ViewBag.issueBidNo = issueBidNo;
            ViewBag.submitBidNo = submitBidNo;
            ViewBag.userName = userName;
            ViewBag.creditAmount = creditAmount;
            ViewBag.discountAmount = (myscore * 0.01).ToString("0.00");
            ViewBag.backAddress = _backAddress;
            ViewBag.sign = GetSign3(array);
            return View();
        }

        //债权Web同步的返回 
        public ActionResult ZhaiQuanConfirmCallBack()
        {
            MyLog.Write("债权投标同步返回开始");
            string errorCode = Request["errorCode"];
            string errorMessage = Request["errorMessage"];
            string timestamp = Request["timestamp"];
            string issueBidNo = Request["issueBidNo"];
            string submitBidNo = Request["submitBidNo"];
            string sign = Request["sign"];
            //验证签名
            string quertString = "" + "errorCode=" + Request["errorCode"] + "&errorMessage=" + Request["errorMessage"] + "&issueBidNo=" + Request["issueBidNo"] +
                "&submitBidNo=" + Request["submitBidNo"] + "&timestamp=" + Request["timestamp"];
            MyLog.WriteLog("债权投标同步返回" + issueBidNo, quertString.Replace("&", "\r"));
            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(quertString, Request["sign"]);
            if (result)
            {
                try //这里是寻找
                {
                    U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["submitBidNo"], 4);//获取投债权的那条记录
                    T_Investment investment = _investService.GetModelBySubmitBidNo(Request["submitBidNo"]);
                    var project = _cservice.GetProjectById(investment.ProjectId.ToString());
                    var amounts = _cservice.GetAmountsByPid(investment.ProjectId.ToString());
                    decimal avaAmounts;
                    if (investment.Status == 1)
                    {
                        avaAmounts = (decimal)project.TotalLoan - amounts;
                    }
                    else
                    {
                        avaAmounts = (decimal)project.TotalLoan - amounts - investment.TenderAmt;
                    }
                    if (avaAmounts <= 0)
                    {
                        //这里又又又改成了手动满标了哎
                        project.TenderStatus = 1;
                        project.TenderTime = DateTime.Now;
                        _pservice.SaveModel(project);
                        //string notifyUrl = _backAddress + "/Pay/ManBiaoNotifyUrl";
                        //if (project.TenderStatus == 0) //表示还没有满标
                        //{
                        //    string strJson = LY.ShengPayApi.Services.Put.PutP2PBidEvent(_merchantNo, project.ProjectNo, 2, notifyUrl, "0.00", _apiAddress);
                        //}
                    }
                    //修改资金流的状态
                    fundsflow.Status = 1;//先改为1
                    fundsflow.AuditTime = DateTime.Now;
                    int j = _fservice.UpdateFundsFlow(fundsflow);
                    investment.Status = 1;//先改为1
                    _investService.SaveInvestment(investment);
                    ViewBag.hehe = "程序处理正确";
                }
                catch (Exception ex)
                {
                    ViewBag.hehe = "程序处理出错";
                }
            }
            else
            {
                ViewBag.hehe = "验证数据失败";
            }
            return View();
        }
        #endregion

        //这个方法就是确定它满了 满标接口
        public ActionResult UpdateProjectOnFullTender(string pid)
        {
            //先调用api接口满标
            T_Project project = _pservice.GetModel(Convert.ToInt32(pid));
            ZCProject zcProject = new ZCProject
            {
                BiaoNo = project.ProjectNo,
            };
            string notifyUrl = _backAddress + "/Pay/ManBiaoNotifyUrl";
            string strJson = LY.ShengPayApi.Services.Put.PutP2PBidEvent(_merchantNo, project.ProjectNo, 2, notifyUrl, "0.00", _apiAddress);
            if (strJson.Contains("请求成功完成"))
            {
                project.TenderStatus = 1;//修改项目为满标状态
                project.TenderTime = DateTime.Now;//满标时间
                _pservice.SaveModel(project);
                //项目还款计划列表
                List<T_RepaymentPlan_EX> repPlanList = _pservice.QueryRepaymentPlanList(Convert.ToInt32(pid));
                DateTime repPlanDate = DateTime.Now.AddDays(1);
                int status = 1;
                for (int i = 0; i < repPlanList.Count; i++)
                {
                    if (i == 0)
                    {
                        status = 2;
                    }
                    if (project.DurationMonthOrDay == 1)
                    {
                        //月份
                        //生成项目收益日期
                        _pservice.UpdateRepaymentPlanDate(repPlanList[i].ID, repPlanDate.AddMonths(i + 1), status);
                    }
                    else if (project.DurationMonthOrDay == 2)
                    {
                        //天数
                        repPlanDate.AddDays((int)project.ProjectDuration);
                        _pservice.UpdateRepaymentPlanDate(repPlanList[i].ID, repPlanDate.AddDays((int)project.ProjectDuration), status);
                    }
                }
            }
            return Json(_cservice.UpdateProject(pid, DateTime.Now, 1));
        }

        public ActionResult UpdateProjectOnEnd(string pid)
        {
            return Json(_cservice.UpdateProject(pid, DateTime.Now, 2));
        }

        //新手专项
        //[HttpPost]
        //public ActionResult GetProjects(int type, int num)
        //{
        //    return Json(_cservice.GetProjects(type, num));
        //}

        //查询用户账户余额（个人）
        public string SelectSftUserBalance()
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            string userName = "";
            if (member != null)
            {
                userName = member.SFTUserName;//"quanju_" + member.Name;
                string sign = "merchantNo=" + _merchantNo + "&userName=" + userName;
                MySign mysign = new MySign();
                string temp = mysign.GetSign(sign);
                string newsign = Server.UrlEncode(temp);
                WebClient webClient = new WebClient();
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                string postString = "?sign=" + newsign;
                string url = _apiAddress + "/userAccount/" + _merchantNo + "-" + userName + postString;
                byte[] postData = Encoding.ASCII.GetBytes(postString);
                byte[] responseData = webClient.DownloadData(url);
                string strJson = Encoding.UTF8.GetString(responseData);
                //验证返回数据
                JavaScriptSerializer js = new JavaScriptSerializer();
                Dictionary<string, string> dic = new Dictionary<string, string>();
                Type type = typeof(Dictionary<string, string>);
                dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
                List<string> test = new List<string>(dic.Keys);
                test.Remove("sign");
                string[] queryString = new string[test.Count];
                for (int i = 0; i < test.Count; i++)
                {
                    queryString[i] = test[i] + "=" + dic[test[i]];
                }
                Array array = queryString;
                Array.Sort(array);
                queryString = (string[])array;
                string hehe = string.Join("&", queryString);
                bool result = mysign.ValidateSign(hehe, dic["sign"]);
                if (result)
                {
                    return strJson;
                }
                else
                {
                    return "数据验证失败";
                }
            }
            else
            {
                return null;
            }
        }

        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        public ActionResult List(FormCollection form, InvestListSearch condition)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<T_Project_EX> plist = _cservice.GetProjects(view, condition);
            for (int i = 0; i < plist.DataList.Count; i++)
            {
                plist.DataList[i].ProjectStatus = _cservice.GetProjects(plist.DataList[i].ID.ToString()).ProjectStatus;
                plist.DataList[i].jindu = Math.Round(_cservice.GetAmountsByPid(plist.DataList[i].ID.ToString()) * 100 / (decimal)plist.DataList[i].TotalLoan, 1);
            }
            JsonQTable at = JsonQTable.ConvertFromPagedList<T_Project_EX>(plist, colkey, colsinfo.Split(','));
            return Json(at);
        }

        //查询余额和是否开通自动投标
        public Dictionary<string, string> GetBalance()
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            string userName = member.SFTUserName;//"quanju_" + member.Name;
            string sign = "merchantNo=" + _merchantNo + "&userName=" + userName;
            MySign mysign = new MySign();
            string temp = mysign.GetSign(sign);
            string newsign = Server.UrlEncode(temp);
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string postString = "?sign=" + newsign;
            string url = _apiAddress + "/userAccount/" + _merchantNo + "-" + userName + postString;
            byte[] postData = Encoding.ASCII.GetBytes(postString);
            byte[] responseData = webClient.DownloadData(url);
            string strJson = Encoding.UTF8.GetString(responseData);
            //验证返回数据
            JavaScriptSerializer js = new JavaScriptSerializer();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Type type = typeof(Dictionary<string, string>);
            dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
            List<string> test = new List<string>(dic.Keys);
            test.Remove("sign");
            string[] queryString = new string[test.Count];
            for (int i = 0; i < test.Count; i++)
            {
                queryString[i] = test[i] + "=" + dic[test[i]];
            }
            Array array = queryString;
            Array.Sort(array);
            queryString = (string[])array;
            string hehe = string.Join("&", queryString);
            bool result = mysign.ValidateSign(hehe, dic["sign"]);
            if (result)
            {
                return dic;
            }
            else
            {
                return null;
            }
        }

        //添加资金流方法
        public void AddFundFlowToDB(U_Member member, int score, string OrderNo, string amount, string projectId)
        {
            //添加资金流
            U_FundsFlow fundsFlow = new U_FundsFlow();
            fundsFlow.OrderNo = OrderNo;
            fundsFlow.MemberId = member.ID;
            double hehe = score * 0.01;
            fundsFlow.OutPay = decimal.Parse(amount) - decimal.Parse((score * 0.01).ToString());//资金记录要扣除积分，就是按照用户实际话费的金额算。
            fundsFlow.CreateTime = DateTime.Now;
            fundsFlow.Status = 0;
            fundsFlow.Type = 4;//表示投债权
            fundsFlow.ProjectId = int.Parse(projectId);
            int j = _fservice.BiaoFundsFlow(fundsFlow);

            //添加投资记录
            T_Investment imvestment = new T_Investment();
            imvestment.ProjectId = int.Parse(projectId);
            imvestment.MemberId = member.ID;
            imvestment.TenderAmt = decimal.Parse(amount); //投资记录还是按照原来的钱算
            imvestment.CreateTime = DateTime.Now;
            imvestment.CreateUser = member.ID.ToString();
            imvestment.Status = 0;
            T_Project project = _pservice.GetProject(int.Parse(projectId));
            imvestment.AnnualisedRates = project.AnnualisedRates;
            imvestment.AddAnnualisedRates = project.AddAnnualisedRates;
            imvestment.SubmitBidNo = OrderNo;
            _investService.SaveInvestment(imvestment);
        }

        

        //债权自动API投标
        public ActionResult ZhaiQuanZiDong()
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            int score = 0;
            //AddFundFlowToDB(member, score, Request["submitBidNo"]);
            string creditAmount = Request["creditAmount"];
            string creditUserName = member.SFTUserName;
            string discountAmount = "0.00";
            string issueBidNo = Request["issueBidNo"];
            string merchantNo = _merchantNo;
            string notifyUrl = _backAddress + "/Pay/ZhaiQuanConfirmApiNotifyUrl";
            string submitBidNo = Request["submitBidNo"];
            string sign = "creditAmount=" + creditAmount + "&creditUserName=" + member.SFTUserName +
                          "&discountAmount=0.00" + "&issueBidNo=" + issueBidNo + "&merchantNo=" + _merchantNo + "&notifyUrl=" + _backAddress + "/Pay/ZhaiQuanConfirmApiNotifyUrl" +
                          "&submitBidNo=" + submitBidNo;
            MySign mysign = new MySign();
            string temp = mysign.GetSign(sign);
            string newsign = Server.UrlEncode(temp);
            WebClient wc = new WebClient();
            StringBuilder postData = new StringBuilder();
            postData.Append("creditAmount=" + creditAmount);
            postData.Append("&creditUserName=" + creditUserName);
            postData.Append("&discountAmount=" + discountAmount);
            postData.Append("&issueBidNo=" + issueBidNo);
            postData.Append("&merchantNo=" + merchantNo);
            postData.Append("&notifyUrl=" + notifyUrl);
            postData.Append("&submitBidNo=" + submitBidNo);
            postData.Append("&sign=" + newsign);
            byte[] sendData = Encoding.UTF8.GetBytes(postData.ToString());
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Headers.Add("ContentLength", sendData.Length.ToString());
            string url = _apiAddress + "/p2pBid/" + merchantNo + "-" + issueBidNo + "/submitBid";
            byte[] recData = wc.UploadData(url, "POST", sendData);
            string strJson = Encoding.UTF8.GetString(recData);
            if (strJson.Contains("请求成功完成"))//同步返回成功
            {
                U_FundsFlow fundsflow1 = _fservice.GetFundsFlowByOrderNo(Request["submitBidNo"], 4);
                fundsflow1.Status = 1;
                fundsflow1.AuditTime = DateTime.Now;
                int k = _fservice.UpdateFundsFlow(fundsflow1);
                T_Investment investment1 = _investService.GetModelBySubmitBidNo(Request["submitBidNo"]);
                investment1.Status = 1;
                _investService.SaveInvestment(investment1);
            }
            //验证返回数据
            JavaScriptSerializer js = new JavaScriptSerializer();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Type type = typeof(Dictionary<string, string>);
            dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
            List<string> test = new List<string>(dic.Keys);
            test.Remove("sign");
            string[] queryString = new string[test.Count];
            for (int i = 0; i < test.Count; i++)
            {
                queryString[i] = test[i] + "=" + dic[test[i]];
            }
            Array array = queryString;
            Array.Sort(array);
            queryString = (string[])array;
            string hehe = string.Join("&", queryString);
            bool result = mysign.ValidateSign(hehe, dic["sign"]);
            if (result)
            {
                return Content("true");
            }
            else
            {
                return Content("false");
            }
        }

        //债权自动API投标的同步返回
        public ActionResult ZhaiQuanZiDongCallBack()
        {
            if (Request["result"] == "true")
            {
                ViewBag.hehe = "验证数据正确";
            }
            else
            {
                ViewBag.hehe = "验证数据失败";
            }
            return View("ZhaiQuanConfirmCallBack");//ZhaiQuanConfirmCallBack

        }


        #region 投资详情
        [MyAuthorization]
        public ActionResult InvestmentInfo(string submitBidNo)
        {
            ViewBag.SubmitBidNo = submitBidNo;

            //根据投标编号，获取投标信息
            T_Investment investment = _investService.GetModelBySubmitBidNo(submitBidNo);
            ViewBag.investmen = investment;
            //获取t_project项目详情
            T_Project_EX Tproject = _cservice.GetProjectById(investment.ProjectId.ToString());
            ViewBag.Tproject = Tproject;
            //获取发标人信息
            U_Member member = _memberService.getMemberInfo(investment.MemberId);
            ViewBag.member = member;
            //获取月偿还本息金额
            T_RepaymentPlan repayment = _pservice.GetRepaymentPlan(investment.ProjectId);
            ViewBag.repayment = repayment;
            //获取回款详情
            List<T_RepaymentPlan_EX> listRepayment = _pservice.GetRPListByProID(investment.ProjectId);
            ViewBag.listRepayment = listRepayment;
            ViewBag.ZQFee = _zQFee;
            return View();
        }
        //下载合同
        [HttpGet]
        public ActionResult Download(string number)
        {
            //判断是否存在PDF文件
            T_Contract contract = _cservice.GetContractByNumber(number);

            //转换成功，向数据库中添加字段  
            String path1 = System.AppDomain.CurrentDomain.BaseDirectory + "contract/" + number + ".pdf";
            String path2 = System.AppDomain.CurrentDomain.BaseDirectory + "contract/" + number + "_Borrower" + ".pdf";
            var zip = "contract/" + number + ".zip";
            var zipPath = System.AppDomain.CurrentDomain.BaseDirectory + zip;


            if (contract == null && !System.IO.File.Exists(zipPath))
            {
                //根据编号获取投表详情
                T_Investment investment = _investService.GetModelBySubmitBidNo(number);
                //获取t_project项目详情
                T_Project_EX Tproject = _cservice.GetProjectById(investment.ProjectId.ToString());
                //获取投标人信息
                U_Member member = _memberService.getMemberInfo(investment.MemberId);
                //发表人信息
                U_CompanyAnnex_EX member1 = _memberService.GetMemberInfo(Tproject.EnterpriseID);
                //获取月偿还本息金额
                T_RepaymentPlan repayment = _pservice.GetRepaymentPlan(investment.ProjectId);

                if (!System.IO.File.Exists(path1))
                {


                    //不存在，转换成pdf 再下载
                    var lable = new LabelName
                        {
                            Number = number,
                            Uniqueness = member.Name,
                            RealName = member.RealName,
                            RealName1 = member.RealName,
                            IDCode = member.IDCode,
                            ConcludeDate = investment.CreateTime.ToString("yyyy年M月d日")
                        };//投资人  

                    var pdf = new ToPdf(lable);
                    pdf.Toprint();


                }
                if (!System.IO.File.Exists(path2))
                {
                    var lable1 = new LabelName
                        {
                            Number = number,
                            CompanyName = member1.CompanyName,
                            Corporation = member1.RealName,
                            CompanyAdrr = member1.ManageAdree,
                            RealName = member.RealName,
                            IDCode = member.IDCode,
                            RmBlowercase = investment.TenderAmt.ToString()
                        };//借款人

                    string RmBcapital = chang1(Convert.ToDecimal(investment.TenderAmt));
                    lable1.RmBcapital = RmBcapital;//借款金额大写
                    decimal rate = (decimal)(Tproject.AnnualisedRates + Tproject.AddAnnualisedRates);
                    lable1.BorrowRate = (rate * 100).ToString();//借款年化利率 

                    lable1.BorrowLimit = Tproject.ProjectDurationStr;//借款期限
                    lable1.ValueDate = "";//起息日
                    lable1.RefundDay = "";//还款日  节假日顺延
                    if (Tproject.LoanTime != null)
                    {
                        lable1.ValueDate = Tproject.LoanTime.ToString();//起息日

                        lable1.RefundDay = Convert.ToDateTime(Tproject.LoanTime).Day.ToString();//还款日
                    }


                    lable1.RefundWay = Tproject.RepaymentTypeStr;//还款方式

                    //DurationMonthOrDay == 1月 DurationMonthOrDay == 2天
                    if (Tproject.DurationMonthOrDay == 1)
                    {
                        //月偿还利息金额
                        lable1.RefundType = "月偿还利息金额";//表格名称
                    }
                    else
                    {
                        //还款总金额
                        lable1.RefundType = "还本付息总额";
                    }

                    if (Tproject.DurationMonthOrDay == 1)
                    {
                        lable1.RefundPrincipal = Math.Round((((decimal)(investment.TenderAmt) * rate / 12) * (decimal)(Tproject.ProjectDuration)), 2).ToString();//本息金额  
                    }
                    else
                    {
                        lable1.RefundPrincipal = Math.Round(((decimal)(investment.TenderAmt) * rate / 365 * ((decimal)(Tproject.ProjectDuration)) + (decimal)(investment.TenderAmt)), 2).ToString();
                    }

                    lable1.HousePlace = Tproject.ProjectAddress;//房屋担保方式


                    lable1.CompanyName1 = member1.CompanyName;//公司名称（后）
                    lable1.Corporation1 = member1.RealName;//法人代表（后）
                    lable1.RealName1 = member.RealName;//投资人（后）
                    lable1.IDCode1 = member.IDCode;//投资人身份证（后） 
                    lable1.ConcludeDate = investment.CreateTime.ToString("yyyy年M月d日");//协议签订日期  

                    var pdf1 = new ToPdf(lable1);
                    pdf1.Toprint1();
                }

                var list = new List<string> { path1, path2 };
                bool isSuc = ZipUtils.CompressMulti(list, zipPath, false);

                if (isSuc)
                {
                    var _contract = new T_Contract
                        {
                            ProjectId = Tproject.ID,
                            ProjectOrderId = Tproject.ProjectNo,
                            Ordernumber = number,
                            Path = zip
                        };
                    int ret = _cservice.SaveContract(_contract);

                    if (ret > 0)
                    {
                        System.IO.File.Delete(path1);
                        System.IO.File.Delete(path2);
                    }

                    ViewBag.Download = Request.ApplicationPath + zip;
                }
                else
                {
                    ViewBag.Download = "";
                }
            }
            else
            {
                try
                {
                    String path = contract.Path;
                    ViewBag.Download = Request.ApplicationPath + path;
                }
                catch
                {
                    ViewBag.Download = "";
                }
            }

            return View();
        }

        //将小写金额转换成大写
        public static string chang1(decimal num)
        {
            string str1 = "零壹贰叁肆伍陆柒捌玖";            //0-9所对应的汉字 
            string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字 
            string str3 = "";    //从原num值中取出的值 
            string str4 = "";    //数字的字符串形式 
            string str5 = "";  //人民币大写金额形式 
            int i;    //循环变量 
            int j;    //num的值乘以100的字符串长度 
            string ch1 = "";    //数字的汉语读法 
            string ch2 = "";    //数字位的汉字读法 
            int nzero = 0;  //用来计算连续的零值是几个 
            int temp;            //从原num值中取出的值 

            num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数 
            str4 = ((long)(num * 100)).ToString();        //将num乘100并转换成字符串形式 
            j = str4.Length;      //找出最高位 
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如：200.55,j为5所以tr2=佰拾元角分 

            //循环取出每一位需要转换的值 
            for (i = 0; i < j; i++)
            {
                str3 = str4.Substring(i, 1);          //取出需转换的某一位的值 
                temp = Convert.ToInt32(str3);      //转换为数字 
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    //当所取位数不为元、万、亿、万亿上的数字时 
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero + 1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                }
                else
                {
                    //该位是万亿，亿，万，元位等关键位 
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零" + str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero + 1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero + 1;
                                }
                            }
                        }
                    }
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    //如果该位是亿位或元位，则必须写上 
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5 + ch1 + ch2;

                if (i == j - 1 && str3 == "0")
                {
                    //最后一位（分）为0时，加上“整” 
                    str5 = str5 + '整';
                }
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5;
        }
        #endregion
        [MyAuthorization]
        public ActionResult ZhuanPan()
        {
            int score = 0;
            if (base.CurrentUser != null)
            {
                //检索个人积分
                score = _scoreService.GetScoreByMID(base.CurrentLoginUserId);
            }
            //积分
            ViewBag.score = score;
            //会员姓名
            ViewBag.memberName = base.Enc_Mobilenumber;
            //中奖名单
            List<T_Prize> prizeList = _scoreService.GetPrizeList();
            ViewBag.prizeList = prizeList;
            return View();
        }

        /// <summary>
        /// 抽取奖项
        /// </summary>
        /// <param name="rates"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetPrize(string length)
        {
            JsonSMsg rMsg = new JsonSMsg();
            if (string.IsNullOrEmpty(length))
            {
                rMsg.Status = -1;
                rMsg.Message = "参数有误！";
                return Json(rMsg);
            }
            //判断有没有登录
            if (base.CurrentUser == null)
            {
                rMsg.Status = -2;
                rMsg.Message = "请您先登录网站再进行抽奖！";
                return Json(rMsg);
            }
            int score = _scoreService.GetScoreByMID(base.CurrentLoginUserId);
            if (score < 200)
            {
                rMsg.Status = -3;
                rMsg.Message = "Sorry：您的积分不足以抽奖！每次抽奖需200积分~";
                return Json(rMsg);
            }

            List<T_Award> awardList = _scoreService.GetAwardList();
            if (awardList == null || awardList.Count == 0)
            {
                rMsg.Status = -4;
                rMsg.Message = "Sorry：奖品池数量不足啦~";
                return Json(rMsg);
            }

            //先判断有没有奖了  
            //["500积分", "智能手环", "5000积分", "1000积分", "iphone6s", "谢谢参与"]
            List<KeyValuePair<int, double>> elements = new List<KeyValuePair<int, double>>();
            Dictionary<int, string> prizeArr = new Dictionary<int, string>();
            for (int i = 0; i < awardList.Count; i++)
            {
                elements.Add(new KeyValuePair<int, double>(i, double.Parse(awardList[i].Rate.ToString())));
                prizeArr.Add(i, awardList[i].AwardName);
            }


            long basicNumber = 0;
            double[] array = new double[elements.Count];
            int m = 0;
            foreach (KeyValuePair<int, double> item in elements)
            {
                array[m] = item.Value;
                m++;
            }

            basicNumber = AwardUtil.GetBaseNumber(array);

            //抽奖
            Random random = new Random();

            long selectedElement = 0;
            long diceRoll = AwardUtil.GetRandomNumber(random, 1, basicNumber);
            long cumulative = 0;

            for (int i = 0; i < elements.Count; i++)
            {
                cumulative += (long)(elements[i].Value * basicNumber);

                if (diceRoll <= cumulative)
                {
                    selectedElement = elements[i].Key;

                    break;
                }
            }

            T_Prize prizeenty = new T_Prize()
            {
                MemberId = base.CurrentLoginUserId,
                MemberName = base.Enc_Mobilenumber,
                Prize = awardList[(int)selectedElement].AwardName,
                Score = awardList[(int)selectedElement].Score,
                Status = false,
                CreateDate = DateTime.Now

            };
            int ret = _scoreService.SavePrize(prizeenty, awardList[(int)selectedElement].Id);
            if (ret > 0)
            {
                rMsg.Status = 1;
                rMsg.Data = awardList[(int)selectedElement].Prize;
            }
            else
            {
                rMsg.Status = -1;
                rMsg.Message = "操作失败！";
            }

            rMsg.Status = 1;
            return Json(rMsg);
        }


        /// <summary>
        /// 积分
        /// </summary>
        /// <returns></returns>
        public ActionResult JiFen()
        {

            return View();
        }

        /// <summary>
        /// 扫码
        /// </summary>
        /// <returns></returns>
        public ActionResult Scan()
        {

            return View();
        }

        //暂时写在这样，过会儿在调整
        public string GetSign3(string[] array)
        {
            MySign mysign = new MySign();
            Array myarray = array;
            Array.Sort(myarray);
            string temp = "";
            for (int i = 0; i < array.Length; i++)
            {
                temp += array[i] + "&";
            }
            temp = temp.Substring(0, temp.Length - 1);
            return mysign.GetSign(temp);
        }

    }


    public class ReturnJson
    {
        public string time { get; set; }
        public string Sign { get; set; }

    }
}
